# -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time    : 2017/12/27 10:42
# @Author  : xincheng.zhao
# @File    : faultview.py
# @Software: PyCharm
import json

from django.http import HttpResponse
from django.shortcuts import render

from bsfault.commen.interface import page, DateEncoder, parentId, signature, reason_x, reason_m
from bsfault.models import info, event, log


def fault_infolist(request):
    J_data = page(info.objects.all().values(), request.GET.get('limit'), request.GET.get('offset'))
    for asset in J_data["data"]:
        J_data["response_data"]['rows'].append(
            {
                'id': asset['fault_id'],
                'events': asset['fault_events'],
                'time': asset['fault_time'],
            })
    return HttpResponse(json.dumps(J_data["response_data"], cls=DateEncoder))


def operate_infolist(request):
    J_data = page(log.objects.all().values(), request.GET.get('limit'), request.GET.get('offset'))
    for asset in J_data["data"]:
        J_data["response_data"]['rows'].append(
            {
                'id': asset['id'],
                'log': asset['log'],
                'time': asset['fault_time'],
            })
    return HttpResponse(json.dumps(J_data["response_data"], cls=DateEncoder))


'''
处理树
'''


def fault_list(request):
    list = []
    for asset in event.objects.all().values():
        list.append(
            {
                'id': asset['id'],
                'events': asset['events'],
                'signature': asset['signature'],
                'describe': asset['describe'],
                'type': asset['type'],
                'parentId': parentId(asset['pid']),
            })
    return HttpResponse(json.dumps(list, cls=DateEncoder))


'''
添加顶事件
'''


def fault_addt(request):
    try:
        log(log=request.session.get('username') + "添加顶事件" + request.GET.get('tevents')).save()
        event(events=request.GET.get('tevents'), pid=0, describe=request.GET.get('describe'), type='T',
              signature='T' + signature()).save()
        id = event.objects.latest('id').id
        event.objects.filter(id=id).update(path='/0/' + str(id) + '/')
        return HttpResponse('ok')
    except:
        return HttpResponse('fail')


'''
删除事件
'''


def fault_del(request):
    try:
        log(log=request.session.get('username') + "删除了与" +
                event.objects.filter(id=request.GET.get('id')).values('events')[0]['events'] + '有关的事件').save()
        path = event.objects.filter(id=request.GET.get('id')).values('path')[0]['path']
        event.objects.filter(path__contains=path).delete()
        # id = event.objects.all().values('id', 'events')
        # for i in id:
        #     print(i)
        #     event.objects.filter(id=i['id']).update(describe=i['events'])
        return HttpResponse('ok')
    except:
        return HttpResponse('fail')


'''
添加事件mx
'''


def fault_addmx(request):
    log(log=request.session.get('username') + "添加事件" + request.POST.get('event')).save()
    path = event.objects.filter(id=request.POST.get('id')).values('path')[0]['path']
    event(events=request.POST.get('event'), describe=request.POST.get('describe'), type=request.POST.get('type'),
          pid=request.POST.get('id'), signature=request.POST.get('type') + signature()).save()
    id = event.objects.latest('id').id
    event.objects.filter(id=id).update(path=path + str(id) + '/')
    return HttpResponse('ok')


'''
更新事件
'''


def fault_upd(request):
    try:
        log(log=request.session.get('username') + "修改事件" + request.POST.get('events')).save()
        event.objects.filter(id=request.POST.get('id')).update(events=request.POST.get('events'),
                                                               describe=request.POST.get('describe'))
        return HttpResponse('ok')
    except:
        return HttpResponse('fail')


def fault_reason(request):
    return render(request, 'reasoning.html')


def get_reason(request):
    list = []
    for asset in event.objects.all().values('id', 'events', 'type'):
        list.append(
            {
                'id': asset['id'],
                'events': asset['events'],
                'type': asset['type'],
            })
    return HttpResponse(json.dumps(list, cls=DateEncoder))


def reason_fault(request):
    x = None
    m = None
    type = event.objects.filter(id=request.GET.get('id')).values('type')[0]['type']
    if type == 'M':
        m = reason_m(request.GET.get('id'))
        return HttpResponse(m)
    else:
        x = reason_x(request.GET.get('id'))
        return HttpResponse(x)



# 故障页面
def fault(request):
    return render(request, 'fault.html')


# 故障信息页面
def faultinfo(request):
    return render(request, 'fault_info.html')


def operate_info(request):
    return render(request, 'operate_info.html')
